const http = require('http');
var url  = require('url');
var querystring  = require('querystring');
var request = require('request');

const fs = require('fs');
const formidable = require('formidable');
const Entities = require('html-entities').XmlEntities;
const entities = new Entities();
const ftpClient = require('ftp');
// const api_address = 'http://192.168.3.9:8015';

var json = '';


// const hostname = '127.0.0.1';
const hostname = '0.0.0.0';
const port = 3000;

const server = http.createServer((req, res) => {

    res.statusCode = 200;
    // res.setHeader('Content-Type', 'text/plain');
    res.setHeader('Content-Type', 'application/json');
    res.setHeader('Access-Control-Allow-Origin','*');
    // console.log( req.url );
    // console.log( url.parse(req.url,true) );

    var url_obj = url.parse(req.url,true);

    var params = url_obj.query;
    var pathname = url_obj.pathname;
    console.log( pathname );
    console.log( req.url );
    console.log( params );
    console.log( req.method );

    if( pathname == '/ftp_upload/'){
        console.log( ' upload file ' );
        upload_file( req, res );
        return;

    }

    //POST
    var str='';
    var POST='';
    req.on('data',function(data){
        str+=data;
    });
    req.on('end',function(){

        try{

            if( !params.api_url ){
                return;
            }

            if( params.api_url.indexOf('update') > -1 ){
                POST = JSON.parse( str );
                if( POST['Del_E_Id'] && typeof POST['Del_E_Id'] == 'object' ){
                    POST['Del_E_Id'] = JSON.stringify( POST['Del_E_Id'] );
                }
                if( POST['Del_V_Id'] && typeof POST['Del_V_Id'] == 'object' ){
                    POST['Del_V_Id'] = JSON.stringify( POST['Del_V_Id'] );
                }
                if( POST['propertyKey'] && typeof POST['propertyKey'] == 'object' ){
                    POST['propertyKey'] = JSON.stringify( POST['propertyKey'] );
                }
            }else{
                POST=querystring.parse(str);
            }

            for(var p in params){
                POST[p] = params[p];
            }
            console.log( POST );
            api_request( POST, res );

        }catch( err ){

            var json = {
                status:1
            };
            res.end( JSON.stringify( json ));
        }


    });


    // req.on('close',function(code, reason){
    //
    //     console.log('req:close');
    //     console.log(code);
    //     console.log(reason);
    // });
    // req.on('error',function(code, reason){
    //
    //     console.log('req:error');
    //     console.log(code);
    //     console.log(reason);
    // });
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});


function api_request( params, server_res ){

    var url = params.api_url;



    request.post({url:url, form:params }, function (error, response, body) {
        // console.log( 'body:\n' );
        // console.log( body );
        server_res.end( body );
    });


}

// 上传文件
function upload_file( req, res ){

    var form = new formidable.IncomingForm();

    form.parse(req, (err, fields, files) => {
        console.log(fields);
        console.log(files);
        const oldpath = files.file.path;
        const ftp_path = fields.ftp_path;
        const newpath = './' + entities.decode(files.file.name)
        // fs.rename(oldpath, newpath, err => {
        //     // fs.unlinkSync( newpath );
        //     if (err) throw err
        //     res.write('File uploaded and moved!')
        //     res.end()
        // });

        var readStream=fs.createReadStream( oldpath );
        // var writeStream=fs.createWriteStream( newpath );
        // readStream.pipe(writeStream);
        // readStream.on('end',function(){
        //     fs.unlinkSync( oldpath );
        //     // res.end( 'success' );
        //
        //     //todo 上传ftp
        //     ftp_upload( res, newpath, ftp_path, fields );
        // });

        // 不通过本地保存，直接上传ftp
        ftp_upload( res, readStream, ftp_path, fields );
    })

}

function ftp_upload( res, file_path, ftp_path, fields ){

    let ftp = new ftpClient();
    let conn = {
        host        : fields.ftp_url        ? fields.ftp_url        : '10.18.221.124',
        port        : fields.ftp_port       ? fields.ftp_port       : '21',
        user        : fields.ftp_user       ? fields.ftp_user       : 'janusftp',
        password    : fields.ftp_password   ? fields.ftp_password   : 'janusftp',

        // host        : '118.190.244.189',
        // port        : '21',
        // user        : 'ftp_test',
        // password    : 'mapping_ftp',

        // host        : '10.18.221.124',
        // port        : '21',
        // user        : 'janusftp',
        // password    : 'janusftp',
    };

    // console.log( 'conn:' );
    // console.log( conn );






    try{
        ftp.connect( conn );
        ftp.on('ready',function(){
            ftp.put( file_path, ftp_path,function( err ){
                if( err ){
                    // throw err;
                    var json = {
                        status:1,
                        description:'ftp上传错误',
                    };
                    res.end( JSON.stringify( json ));
                }

                ftp.end();
                var json = {
                    status:0
                };
                res.end( JSON.stringify( json ));
            });

        });

    }catch( err ){

        var json = {
            status:1
        };
        res.end( JSON.stringify( json ));
    }

}